define(["jquery", "bbcare",
    "scprit/department/vm/assessmentScreening/peabodyScale.ui.js",
    "scprit/department/vm/assessmentScreening/assessmentScreeningQuestion.servers.js"], function ($,$bb,$ui,$servers) {
    var event = {
        _vm: null,
        userInfo: null,
        showToast: true,
    };
    
    event._vm = null;
    event.userInfo = null;
    event.initVm = function (fn) {
        event._vm = null;
        event._vm = new Vue({
            el: '.bg-white',
            data: {
                loading: false,
            },
            created: function () {
                var data = $('.content-main').data()
                if (!data.params.testTime) {
                    this.getRecord();
                } 
            },
            methods: {
                getRecord: function () {
                    var params = $bb.getPageParams(), that = this;
                    $servers.getDraft(params.userId, function (res) {
                        if (!res.success) return;
                        that.$confirm('检测到您有一份未做完的测评，你需要继续填写吗？', '提示', {
                            type: 'warning',
                            cancelButtonText: '重新填写',
                            confirmButtonText: '继续填写',
                        }).then(function () {
                            // event._vm.loading = true;
                            setTimeout(function () {
                                that.render(res);
                            }, 200);
                        }).catch(function () {
                            event.showToast = true;
                            console.log('点击重新填写则不处理本身就是新的题目');
                        });
                    });
                },
                render: function (params) {
                    fn(event.userInfo, params)
                }
            }
        })
    }

    /**
     * 根据月龄查id
     */
    var getGoingIdByMonth = function(list,month){
        for (var i = 0; i < list.length; i++) {
            if( list[i].moonage.indexOf("~") < 0 ){
                if( parseInt(list[i].moonage) == parseInt(month) ){
                    return list[i].id;
                }
            }else{
                var minMonth = list[i].moonage.substring(0,list[i].moonage.indexOf("~"));
                var maxMonth = list[i].moonage.substring(list[i].moonage.indexOf("~")+1,list[i].moonage.length);
                if( parseInt(month) >= parseInt(minMonth) && parseInt(month) <= parseInt(maxMonth) ){
                     return list[i].id;
                }
            }
        }
    }
    event.getGoingIdByMonth = function(list,month){
        return getGoingIdByMonth(list,month);
    }
    /**
     * 将题目的月龄提出来
     */
    var getMonthAgeTotal = function(list){
        var arr = [];
        for (var i = 0; i < list.length; i++) {
            arr.push( list[i].moonage );
        }
        for (var i = arr.length - 1; i >= 1; i--) {
            for (var j = i-1 ; j >= 0; j--) {
                if( arr[i] == arr[j] ){
                    arr.splice(i,1);
                }
            }
        }
        return arr;
    }
    event.getMonthAgeTotal = function(list){
        return getMonthAgeTotal(list);
    }
    /**
     * 获取输入的月龄是否存在
     */
    var getFlagMonthAge = function(list,text){
        for (var i = 0; i < list.length; i++) {
            if( list[i].indexOf("~") < 0 ){
                if( list[i] == text ) return true;
            }else{
                var minNum = list[i].substring(0,list[i].indexOf("~"));
                var maxNum = list[i].substring(list[i].indexOf("~")+1,list[i].length);
                if( text >= minNum && text <= maxNum ) return true;
            }
        }
        return false;
    }
    event.getFlagMonthAge = function(list,text){
        return getFlagMonthAge(list,text);
    }
    event.tabClick = function(monthAge,data,scoreObj,ids){
        var _this = this;
        $("#testSelect").on('click','div',function(){
            isChecked(scoreObj);
            var nextId = $(this).attr("nextId");
            var tabName = $(this).attr("ques");
            var quesType = _this.getQuesType(tabName);
            $(this).addClass('checking').removeClass("checked").siblings().removeClass('checking');
            var dataInit = _this.quesDeal(monthAge,data[tabName],tabName,nextId);
            $ui.peabodyInit({"id":"#question","data":dataInit.data});
            $ui.scoreTabInit({"id":"#scores-show","data":dataInit.scoresTab});
            // begin 自定义起始月龄
            $("#userDefinedMonth").css({"display":"block"});
            $("#userDefinedMonth button").unbind("click");
            $("#userDefinedMonth button").click(function(){
                var text = $(this).parent().prev().val();
                var reg = /^[0-9]+$/;
                if( !reg.test(text) ){
                    $bb.toastShow("请输入数字！",1500);
                }else{
                    var arrMonthAgeTotal = getMonthAgeTotal(dataInit.data);
                    $("#userDefinedMonth input").val("");
                    if( !getFlagMonthAge(arrMonthAgeTotal,text) ){
                        var str = arrMonthAgeTotal.join("、");
                        $bb.toastShow("请输入年龄范围在"+ str +"月龄之中！");
                    }else{
                        var goingId = getGoingIdByMonth(dataInit.data,text);
                        var dataInit1 = _this.quesDeal(monthAge,data[tabName],tabName,goingId);
                        $ui.peabodyInit({"id":"#question","data":dataInit1.data});
                        $ui.scoreTabInit({"id":"#scores-show","data":dataInit1.scoresTab});
                        $(this).parent().prev().val(text)
                        sessionStorage.setItem('peabody_scale_start_month', text)
                    }
                }
            });
            // end 自定义起始月龄
            var isEnding = $(this).attr('isEnding');
            var bottomId = $(this).attr("bottomId");
            var topId  = $(this).attr("topId");
            if( isEnding == 'end'){
                $("#scores-show").off('mousedown mouseup','div.fractional-item');
            }else{
                _this.scoreClick(dataInit.data,scoreObj,topId,bottomId,ids);
                _this.topAndBottomInit([]);
            }
            drawTopAndBottom(this,scoreObj,quesType);
        });
    };
    event.scoreClick = function(data,scoreObj,topId,bottomId,ids){
        $("#scores-show").off('mousedown mouseup','div.fractional-item');
        var endId =data.length*1;
        var _this = this;
        var quesType,id,result;
        var flagTop = topId ? true : false;
        var flagBottom = bottomId ? true : false;
        var topId,bottomId,isEnding;
        $("#scores-show").on('mousedown','div.fractional-item',function(){
            $(this).addClass('down');
            var score = $(this).attr("score");
            quesType = $("#quesId").attr("quesType");
            id = $("#quesId").val();
            
            if(score == 0){
                data[id-1].value = 0;
                $("#"+quesType+"-"+id).find('li').eq(0).html('<img src="page/department/img/00.png">');
            }else if(score == 1){
                data[id-1].value = 1;
                $("#"+quesType+"-"+id).find('li').eq(0).html('<img src="page/department/img/01.png">');
            }else if(score == 2){
                data[id-1].value = 2;
                $("#"+quesType+"-"+id).find('li').eq(0).html('<img src="page/department/img/02.png">');
            }
            scoreObj[quesType][id] = score;
            result = _this.jumpNext(id,1,endId,quesType,scoreObj);
        });

        $("#scores-show").on('mouseup','div.fractional-item',function(){
            $(this).removeClass('down');
            $("#"+quesType+"-"+id).removeClass('now-item').addClass('disable');
            //获取下一题id：
            if(result.nextId*1 >= 0 ){
                id = result.nextId;
            } else {
                var isArr = result.idArr;
                if(isArr[3] == result.max){//向下走：
                    if(scoreObj[quesType][isArr[0]] == 2 && scoreObj[quesType][isArr[1]] == 2 && scoreObj[quesType][isArr[2]] == 2 && scoreObj[quesType][isArr[3]] == 2){
                        id = isArr[3] + 1;
                    }else if(scoreObj[quesType][isArr[0]] == 2 && scoreObj[quesType][isArr[1]] == 2 && scoreObj[quesType][isArr[2]] == 2 && scoreObj[quesType][isArr[3]] != 2){
                        if(!flagBottom){
                            if (event.showToast) {
                                $bb.toastShow("底部确定",1500);
                            }
                            bottomId = result.idArr;
                            flagBottom= true;
                            id = isArr[3] + 1;
                        }else{
                            if(!flagTop){id = isArr[3] + 1;}
                        }
                    }else if(scoreObj[quesType][isArr[0]] != 0 && scoreObj[quesType][isArr[1]] == 0 && scoreObj[quesType][isArr[2]] == 0 && scoreObj[quesType][isArr[3]] == 0){
                        topId = result.idArr;
                        flagTop = true;
                        //$bb.toastShow("顶部确定,该部分测试已经完成，即将进入下一项测试",2000);
                    }else{
                        if(!flagTop){id = isArr[3] + 1;}
                    }
                }else if(isArr[3] == result.min){//往上走：
                    if(scoreObj[quesType][isArr[0]] == 0 && scoreObj[quesType][isArr[1]] == 0 && scoreObj[quesType][isArr[2]] == 0 && scoreObj[quesType][isArr[3]] > 0){
                        if (event.showToast) {
                            $bb.toastShow("顶部确定",1500);
                        }
                        topId = result.idArr;
                        flagTop = true;
                        if(flagBottom){
                            $bb.toastShow("该部分测试已经完成",1500);
                        }else{
                            id = isArr[3] - 1;
                        }
                    }else if(scoreObj[quesType][isArr[0]] < 2 && scoreObj[quesType][isArr[1]] == 2 && scoreObj[quesType][isArr[2]] == 2 && scoreObj[quesType][isArr[3]] == 2){
                        bottomId = result.idArr;
                        flagBottom = true;
                        if(flagTop){
                           // $bb.toastShow("底部确定，该部分测试已经完成，即将进入下一项测试",2000);
                        }else{
                            if(!flagBottom){
                                id = isArr[3] - 1;
                            }else if(!flagTop){
                                $bb.toastShow("底部确定",1500);
                                id = result.max + 1;
                            }
                        }
                    }else{
                        id = isArr[3] - 1;
                    }
                }
                if(flagBottom){//底部
                    scoreObj.bottom[quesType] = bottomId;
                    $("#"+quesType).parent().attr('bottomId',JSON.stringify(bottomId));
                    var resBottom = topAndBottom(bottomId,scoreObj,quesType);
                    $ui.bottomScoreInit({"id":"#bottom-score","data":resBottom})
                }
                if(flagTop){//顶部
                    scoreObj.top[quesType] = topId;
                    $("#"+quesType).parent().attr('topId',JSON.stringify(topId));
                    var resTop =topAndBottom(topId,scoreObj,quesType);
                    $ui.topScoreInit({"id":"#top-score","data":resTop})
                }
            }
            
            if(id*1 == 0){
                if(!(flagTop && flagBottom)){$("#"+quesType).html(0 +'分');}
                var tplDialog = {
                    title:"提示",
                    tips:"最低水平无法完成，记0分",
                    btn1:"重新测评",
                    btn0:"进行下一项"
                };
                $("#scores-show").off('mousedown mouseup','div.fractional-item');
                isEnding =  'end';
                $("#"+quesType).parent().attr({'nextId':id*1+1,'isEnding':isEnding});
                var callback1 = function(){
                    var params = $("#quesId").attr("quesType");
                    $("#"+params).parent("div").removeAttr("nextId topId bottomId isEnding").click();
                    scoreObj[params] = {};
                    event.refresh();
                };
                var callback0 = function(params){
                    var param = $("#quesId").attr("quesType");
                    ids = _this.delId(ids,param);
                    if(ids.length>0){
                        $("#"+ids[0]).parent().click();
                    }else{
                        $bb.toastShow("所有项目已经全部完成",2000);
                    }
                };
                _this.dialog(tplDialog,callback1,callback0,scoreObj);
            }else{
                var totalScore = _this.totalScore(scoreObj,quesType,topId,bottomId);
                var start = sessionStorage.getItem('peabody_scale_start_month')
                if(id*1 > endId*1){
                    $("#scores-show").off('mousedown mouseup','div.fractional-item');
                    isEnding =  'end';
                    $("#"+quesType).html(totalScore+'分').parent().attr('isEnding',isEnding);
                    ids = _this.delId(ids,quesType);
                    var tips;
                    if(ids.length>0){
                        tips = '该项测试题目已全部做完,即将进入下一项测试';
                    }else{
                        tips = '项目测试已经全部完成';
                    }
                    if (event.showToast) {
                        $bb.toastShow(tips,2000);
                        if(ids.length>0){
                            setTimeout(function(){
                                $("#"+ids[0]).parent().click();
                                if (start) {
                                    $('#sure').click()
                                    $('#sure').parent().prev().val(start)
                                }
                            },2000)
                        }
                    } else {
                        $("#"+ids[0]).parent().click();
                        if (start) {
                            $('#sure').click()
                            $('#sure').parent().prev().val(start)
                        }
                    }
                    
                }else{
                    if(flagTop && flagBottom){
                        $("#scores-show").off('mousedown mouseup','div.fractional-item');
                        isEnding = 'end';
                        $("#"+quesType).parent().attr('isEnding',isEnding);
                        ids = _this.delId(ids,quesType);
                        var tips;
                        if(ids.length>0){
                            tips = '该项测试底部和顶部已全部找到,即将进入下一项测试';
                        }else{
                            tips = '该项测试底部和顶部已全部找到，全部测试已经完成';
                        }
                        if (event.showToast) {
                            $bb.toastShow(tips,2000);
                            if(ids.length>0){
                                setTimeout(function(){
                                    $("#"+ids[0]).parent().click();
                                    if (start) {
                                        $('#sure').click()
                                        $('#sure').parent().prev().val(start)
                                    }
                                },2000)
                            }
                        }
                    }
                    $("#"+quesType).html(totalScore+'分').parent().attr({'nextId':id,'isEnding':isEnding});
                    isShow(id*1,1,endId*1,quesType);
                    var scoreTab = $("#"+quesType+"-"+id).attr('score');
                    scoreTab = _this.scoreTabDeal(JSON.parse(scoreTab));
                    $ui.scoreTabInit({"id":"#scores-show","data":scoreTab});
                }
            }
        });
    };


    //默认展示的题目处理：
    event.quesDeal = function(monthAge,data,quesType,goingId){
            
        var _this = this;
        var scoresTab,startId;
        var type = _this.getQuesType(quesType);

        for(var i = 0 ;i<data.length ; i++){
            data[i].type = type;
            data[i].score.type = type;
            data[i].score.id = data[i].id;
            data[i].oprationFlag = false;
            if(data[i].value >= 0 && !goingId){
                delete data[i].value;
            }
            if(!goingId){
                var origin = data[i].origin;
                if(origin){
                    var monthStart = origin.substring(2,origin.indexOf("月"));
                    if(monthStart.indexOf("~")!="-1"){
                        var first = monthStart.substring(0,monthStart.indexOf("~"));
                        var last = monthStart.substring(monthStart.indexOf("~")+1,monthStart.length);
                        if(monthAge >= first*1 && monthAge <= last*1){
                            data[i].oprationFlag = true;
                            scoresTab =  data[i].score;
                            scoresTab.id = startId =data[i].id;
                        }
                    }else if(monthStart*1 == monthAge){
                        data[i].oprationFlag = true;
                        scoresTab =  data[i].score;
                        scoresTab.id = startId = data[i].id;
                    }
                }
                if(typeof data[i].score == 'object'){
                    data[i].score = JSON.stringify(data[i].score);
                }
            }else{
                if(data[i].id == goingId*1){
                    data[i].oprationFlag = true;
                    scoresTab =  data[i].score;
                    scoresTab.id = startId = data[i].id;
                }
                if(data[i].id != goingId*1){
                    if(data[i].oprationFlag == true){
                        data[i].oprationFlag = false;
                    }
                }
                if(typeof data[i].score == 'object'){
                    data[i].score = JSON.stringify(data[i].score);
                }
            }
        }
        if(!goingId){
            //如果查不到起始月龄，默认展示第一题：
            if(typeof scoresTab == 'undefined'){
                data[0].oprationFlag = true;
                scoresTab =  data[0].score;
                scoresTab.id = startId = data[0].id;
            }
        }
        scoresTab = _this.scoreTabDeal(scoresTab);
        data = _this.quesShowLength(startId, data);
        return {
            'data':data,
            'scoresTab':scoresTab,
            'initId':startId
        }
    };
    event.quesDealAndRecord = function (monthAge,data,quesType, answerResult) {
        var _this = this;
        var scoresTab,startId;
        var type = _this.getQuesType(quesType);
        for(var i = 0 ;i<data.length ; i++){
            data[i].type = type;
            data[i].score.type = type;
            data[i].score.id = data[i].id;
            data[i].oprationFlag = false;
            if(data[i].value >= 0){
                delete data[i].value;
            }
            var origin = data[i].origin;
            if(origin){
                var monthStart = origin.substring(2,origin.indexOf("月"));
                if(monthStart.indexOf("~")!="-1"){
                    var first = monthStart.substring(0,monthStart.indexOf("~"));
                    var last = monthStart.substring(monthStart.indexOf("~")+1,monthStart.length);
                    if(monthAge >= first*1 && monthAge <= last*1){
                        data[i].oprationFlag = true;
                        scoresTab =  data[i].score;
                        scoresTab.id = startId =data[i].id;
                    }
                }else if(monthStart*1 == monthAge){
                    data[i].oprationFlag = true;
                    scoresTab =  data[i].score;
                    scoresTab.id = startId = data[i].id;
                }
            }
            if(typeof data[i].score == 'object'){
                data[i].score = JSON.stringify(data[i].score);
            }
        }
        
        scoresTab = _this.scoreTabDeal(scoresTab);
        data = _this.quesShowLength(startId, data);

        for (var j = 0; j < data.length; j++) {
            var id = data[j].id;
            var score = answerResult[event.getQuesType(quesType)][id]
            if (score >= 0) {
                data[j].value = score;
                if( typeof data[j].score =='object'){
                    data[j].score.value = score;
                    data[j].score.type = event.getQuesType(quesType);
                    data[j].score = JSON.stringify(data[j].score);
                }
            }
        }
        var idArr  = [];
        for(var ids in answerResult[event.getQuesType(quesType)]){
            idArr.push(ids);
        }
        var endId  = Math.max.apply(null, idArr);


        return {
            'data':data,
            'scoresTab':scoresTab,
            'initId':endId,
        }
    }

    //默认展示题目展示长度为9：
    event.quesShowLength = function(startId,data){
        var quesLength  = data.length;
        for(var i=0;i<data.length;i++){
            if(startId < 5){
                if(data[i].id <= 9){
                    data[i].showFlag = true;
                }else{
                    data[i].showFlag = false;
                }
            }else if(quesLength - startId < 4){
                if(data[i].id >= quesLength - 9 ){
                    data[i].showFlag = true;
                }else{
                    data[i].showFlag = false;
                }
            }else{
                if(data[i].id >= startId - 4 && data[i].id <= startId*1 + 4 ){
                    data[i].showFlag = true;
                }else{
                    data[i].showFlag = false;
                }
            }
        }
        return data;
    };
    //分数项处理：
    event.scoreTabDeal = function(scoreObj){
        if( typeof scoreObj == 'string'){
            scoreObj = JSON.parse(scoreObj);
        }
        for(var item in scoreObj){
            if(!isNaN(item)){
                scoreObj["score"+item] = scoreObj[item];
            }
        }
        return scoreObj;
    };
    //跳到下一题：flag 用来判断找顶部（dowm）还是找底部(up)；
    event.jumpNext = function(nowId,startId,endId,quesType,scoreObj){
        // debugger
        var nextId;
        var nowScore = scoreObj[quesType][nowId];//获取当前题目得分情况；
        var arr = [], arrLens,idArr = [];
        for(var item in scoreObj[quesType]){
            arr.push(item*1);
        }
        var min  = Math.min.apply(null, arr);
        var max  = Math.max.apply(null, arr);
        arrLens = arr.length;
        if(arrLens >= 3){
            if(arrLens == 3){
                if(scoreObj[quesType][nowId*1-1] == 2 && scoreObj[quesType][nowId*1 - 2] == 2){//往下走
                    if(scoreObj[quesType][nowId*1] == 2){
                        nextId = nowId*1 + 1;
                    }else{
                        nextId = nowId*1 - 3;
                    }
                }else{//往上走
                    if(scoreObj[quesType][nowId*1] == 2 && scoreObj[quesType][nowId*1+1] == 2 && scoreObj[quesType][nowId*1+2] == 2){
                        nextId = nowId*1 + 3;
                    }else{
                        nextId = nowId*1 - 1;
                    }
                }
            }else{
                if(nowId *1 == max){//往下走
                    idArr = [nowId*1 - 3, nowId*1 - 2,nowId*1 - 1,nowId*1];//当前id最大
                }else if(nowId *1 == min){//往上走
                    idArr = [nowId*1 + 3, nowId*1 + 2,nowId*1 + 1,nowId*1]; //当前id最小；
                }
            }
        }else{
            if(arrLens == 1){
                if(nowScore == 2){
                    nextId = nowId*1 + 1;
                }else{
                    nextId = nowId*1 - 1;
                }
            }else if(arrLens == 2){
                if(scoreObj[quesType][nowId*1 - 1] == 2 ){//往下走：
                    if(scoreObj[quesType][nowId*1] == 2){
                        nextId = nowId*1 + 1;
                    }else{
                        nextId = nowId*1 - 2;
                    }
                }
                if(scoreObj[quesType][nowId*1 + 1] < 2){//往上走:第一次就不是2，
                    nextId = nowId*1 - 1;
                }
            }
        }
        return {
            'nextId':nextId,
            'idArr':idArr,
            'min':min,
            'max':max
        };
    };
    var isShow = function(nowId,startId,endId,quesType){
        if(nowId < 5){
            for(var i = 0 ; i< 9;i++){
                if($("#"+quesType+"-"+(i+1)).hasClass("ques-hide")){
                    $("#"+quesType+"-"+(i+1)).removeClass("ques-hide");
                }
                if(nowId == i+1 ){
                    $("#"+quesType+"-"+(i+1)).removeClass("disable").addClass('now-item');
                }
            }
        }else if(endId - nowId < 4){
            for(var i = endId  ; i< endId -10 ;i--){
                if($("#"+quesType+"-"+ i).hasClass("ques-hide")){
                    $("#"+quesType+"-"+ i).removeClass("ques-hide");
                }
            }
            $("#"+quesType+"-"+nowId).removeClass('disable').addClass("now-item");
        }else{
            for(var i = nowId - 4 ; i<=  nowId*1 + 5 ;i++){
                if($("#"+quesType+"-"+ i).hasClass("ques-hide")){
                    $("#"+quesType+"-"+ i).removeClass("ques-hide");
                }
                $("#"+quesType+"-"+ (nowId*1 - 5)).removeClass('now-item').addClass('ques-hide');
                if(nowId*1 == i ){
                    $("#"+quesType+"-"+ i).removeClass("disable").addClass('now-item');
                }

            }
            for(var i = startId*1 ; i< nowId - 4 ;i++){
                if(!$("#"+quesType+"-"+i).hasClass("ques-hide")){
                    $("#"+quesType+"-"+ i).removeClass('now-item').addClass('ques-hide');
                }
            }
            for(var i = nowId*1 + 5 ; i<=  endId  ;i++){
                if(!$("#"+quesType+"-"+i).hasClass("ques-hide")){
                    $("#"+quesType+"-"+ i).removeClass('now-item').addClass('ques-hide');
                }
            }
        }
    };
    //底部和顶部数组结构处理：
    var topAndBottom = function(arr,scoreObj,quesType){
        var result = {}, list;
        if(typeof arr == 'string'){
            list = event.getObj(arr);
        } else {
            list = arr;
        }
        arr = list.sort(function(a, b){ return a - b });
        result.score0= arr[0];
        result.scoreId0= scoreObj[quesType][arr[0]];
        result.score1= arr[1];
        result.scoreId1= scoreObj[quesType][arr[1]];
        result.score2= arr[2];
        result.scoreId2= scoreObj[quesType][arr[2]];
        result.score3= arr[3];
        result.scoreId3= scoreObj[quesType][arr[3]];
        return result;
    };
    //计算总分：topId,bottomId:顶部和底部的id数组：
    event.totalScore = function(scoreObj,quesType,topId,bottomId){
        var totalScore = 0;
        var itemArr = [];

        for(var item in scoreObj[quesType]){
            if(topId){//顶部
                if(typeof topId == 'string'){
                    topId = event.getObj(topId);
                }
                var topMaxId = Math.max.apply(null, topId);
                if(item *1 > topMaxId){
                    delete scoreObj[quesType][item];
                    continue;
                }
            }
            totalScore +=scoreObj[quesType][item]*1;
            itemArr.push(item*1);
        }
        if(bottomId){//底部
            if(typeof bottomId == 'string'){
                bottomId = event.getObj(bottomId);
            }
            var bottomMinId = Math.min.apply(null, bottomId);
            var itemArrMinId  = Math.min.apply(null, itemArr);
            if(bottomMinId > itemArrMinId){
                totalScore += (itemArrMinId-1)*2;
            }else{
                totalScore += (bottomMinId-1)*2;
            }
        }
        return totalScore;
    };
    event.getObj = function (obj) {
        if (typeof obj == 'string') {
            obj = JSON.parse(obj);
            if (typeof obj == 'string') {
                return event.getObj(obj);
            }
            return obj
        } else {
            return obj
        }
    }
    event.submit = function(type ,userId,scoreObj,doctorDom){
        var itemTotalScore = {};//存放项目总分：
        var submissionResult = function(){
            var business  = $.trim($(doctorDom).val());
            business  = business ? business : "评估医生";
            var notDo = [];
            for(var item in scoreObj){
                var val;
                val= $("#"+item).html();
                var score = val ? val.substring(0,val.length-1) : 0 ;
                itemTotalScore[item] = isNaN(score) ? 0 :score*1;
                var isEnding = $("#"+item).parent().attr("isEnding");
                var ques = $("#"+item).parent().attr("ques");
                if(isEnding != "end" && ques){notDo.push(ques);}
            }
            //提交分数：
            var getScoreFn = function(result){
                event._vm.loading = false;
                $bb.openPage('peabodyScaleResult',{
                    "type":type,
                    "userId":userId
                });
            };
            scoreObj.itemTotalScore = itemTotalScore;
            if($.isEmptyObject(notDo)){
                var scoreParams = $servers.scoreParams(type,scoreObj,'',userId, business);
                event._vm.loading = true;
                scoreParams.testTime = $($('#basicInfo label')[2]).text().split('：')[1];
                $servers.getScore(scoreParams,getScoreFn);
            }else{
                var tips = notDo.join('、')+"问卷还没有做完，请全部做完之后再提交！";
                $bb.toastShow(tips,2000);
            }
        }

        /**
         * 暂存
         */
        var saveCallback = function () {
            var business  = $.trim($(doctorDom).val());
            business  = business ? business : "评估医生";
            scoreObj.itemTotalScore = itemTotalScore;
            var scoreParams = $servers.scoreParams(type,scoreObj,'',userId, business);
            scoreParams.testTime = $($('#basicInfo label')[2]).text().split('：')[1];
            var saveScoreCallback = function (result) {
                event._vm.loading = false;

                event._vm.$message.success(result ? '暂存成功' : '暂存失败');
            }
            event._vm.loading = true;
            $servers.getTemporaryScore(scoreParams, saveScoreCallback);
        }

        var topbars = [
            {
                "icon":"fa fa-print",
                "name":"提交结果",
                "callback":submissionResult
            },
            {
                "icon":"fa fa-floppy-o",
                "name":"暂存结果",
                "callback": saveCallback
            }
        ];
        $bb.toolbar(topbars);
    };
    event.getQuesType = function(quesType){
        return quesType == "反射" ? "reflex":quesType == "姿势" ? "posture":quesType == "移动" ? "motion":quesType == "抓握" ? "grab":quesType == "视觉-运动" ? "visuomotor":quesType == "实物操作" ? "practice":'';
    };
    //问卷记录渲染数据处理：
    event.quesRecord  = function(data,tabName,answerResult){
        var _this = this;
        var quesType = _this.getQuesType(tabName);
        for(var i = 0;i< data[tabName].length;i++) {
            var id = data[tabName][i].id;
            if (answerResult[quesType][id] >= 0) {
                data[tabName][i].value = answerResult[quesType][id];
                if( typeof data[tabName][i].score =='object'){
                    data[tabName][i].score.value = answerResult[quesType][id];
                    data[tabName][i].score.type = quesType;
                    data[tabName][i].score = JSON.stringify(data[tabName][i].score);
                }
                data[tabName][i].showFlag = true;
                data[tabName][i].oprationFlag = true;
                data[tabName][i].type = quesType;
            }
        }
        var idArr  = [];
        for(var ids in answerResult[quesType]){
            idArr.push(ids);
        }
        var startId  = Math.min.apply(null, idArr);
        var endId  = Math.max.apply(null, idArr);
        
        return {
            "data":data,
            "minId":startId,
            "maxId":endId
        } ;
    };
    event.tabClick2 = function(monthAge,data,answerResult, draft){
        var _this = this;
        $("#testSelect").on('click','div',function(){
            isChecked(answerResult);
            var tabName = $(this).attr("ques");
            var quesType = _this.getQuesType(tabName);
            if($.isEmptyObject(answerResult[quesType])) {
                var dataInit = _this.quesDeal(monthAge,data[tabName],tabName,'');
                $ui.peabodyInit({"id":"#question","data":dataInit.data});
                $ui.scoreTabInit({"id":"#scores-show","data":dataInit.scoresTab});
            } else if (draft) {
                var dataInit = _this.quesDeal(monthAge,data[tabName],tabName, '');
                $ui.peabodyInit({"id":"#question","data":dataInit.data});
                $ui.scoreTabInit({"id":"#scores-show","data":dataInit.scoresTab});
            } else{
                var dataInit2 = _this.quesRecord(data,tabName,answerResult);
                $ui.peabodyInit({"id":"#question","data":dataInit2.data[tabName]});
                var id = "#"+quesType+"-"+dataInit2.minId;
                _this.scoreInit(id);
            }
            $(this).addClass('checking').removeClass("checked").siblings().removeClass('checking');
            drawTopAndBottom(this,answerResult,quesType);
        });
    };
    event.quesClick = function(){
        var _this = this;
        $("#question").on('click','ul',function(){
            _this.scoreInit(this);
            $(this).addClass('his').siblings().removeClass('his');
        });
    };
    event.scoreInit = function(dom){
        var score = $(dom).attr("score");
        if(typeof score == 'string'){
            score = JSON.parse(score);
        }
        $(dom).addClass('his').siblings().removeClass('his');
        var scoreTab = this.scoreTabDeal(score);
        $ui.scoreTabInit({"id":"#scores-show","data":scoreTab});
    };
    event.topAndBottomInit = function(answerResult,tabName){
        var quesType = this.getQuesType(tabName);
        var resTop = {},resBottom = {};
        //获取顶部：
        if(!$.isEmptyObject(answerResult[quesType])){
            var topId = answerResult.top[quesType];
            if(!$.isEmptyObject(topId)){
                resTop = topAndBottom(topId,answerResult,quesType);
            }
        }
        if(!$.isEmptyObject(answerResult[quesType])){
            var bottomId = answerResult.bottom[quesType];
            if(!$.isEmptyObject(bottomId)){
                resBottom = topAndBottom(bottomId,answerResult,quesType);
            }
        }
        $ui.topScoreInit({"id":"#top-score","data":resTop});
        $ui.bottomScoreInit({"id":"#bottom-score","data":resBottom});
    };
    //问卷记录 itemtab数据处理：
    event.tabAttr = function(tabArr,answerResult){
        for(var i = 0;i<tabArr.length;i++){
            var id  = tabArr[i].id;
            tabArr[i].score  = answerResult.itemTotalScore[id];
            if(answerResult.bottom){tabArr[i].bottomId  = JSON.stringify(answerResult.bottom[id]);}
            if(answerResult.top){tabArr[i].topId  = JSON.stringify(answerResult.top[id]);}
        }
    };
    var isChecked = function(scoreObj){
        for(var item in scoreObj){
            if(!$.isEmptyObject(scoreObj[item])){
                $("#"+item).parent('div').addClass("checked");
            }
        }
    };
    var drawTopAndBottom = function(dom,scoreObj,quesType){
        var bottomId = $(dom).attr("bottomId");
        var topId  = $(dom).attr("topId");
        var resTop={}, resBottom={};
        if(topId){resTop =topAndBottom(JSON.parse(topId),scoreObj,quesType);}
        if(bottomId){resBottom = topAndBottom(JSON.parse(bottomId),scoreObj,quesType);}
        $ui.topScoreInit({"id":"#top-score","data":resTop});
        $ui.bottomScoreInit({"id":"#bottom-score","data":resBottom});
    };
    //获取起始月龄判断：
    event.getMonthAge = function(acturalDay,pregnanceDay){
        var monthAge;
        if(acturalDay/365 >= 2){
            monthAge = Math.floor(acturalDay/30.4);
        }else{
            if(pregnanceDay < 37*7){
                var dayDiff = acturalDay - (280 - pregnanceDay);
                if(dayDiff <= 0){
                    monthAge = 0;
                }else{
                    monthAge = Math.floor(dayDiff/30.4);
                }
            }else{
                monthAge = Math.floor(acturalDay/30.4);
            }
        }
        return monthAge;
    };
    /*
     * 弹窗事件：
     * tpl:渲染弹窗的字段；
     * callback1 :按钮的flag==1 的回调函数；
     * callback0 :按钮的flag==0 的回调函数；
     * params:其他参数
     * */
    event.dialog = function(tplDialog,callback1,callback0,params){
        $ui.dialogInit({"id":"#modal","data":tplDialog});
        $("#modal").off("click",".modal-footer>button");
        $("#modal").on("click",".modal-footer>button",function(){
            var flag = $(this).attr("flag");
            if(flag == "1"){
                if(callback1 && typeof callback1 == 'function'){
                    params ? callback1(params):callback1();
                }
            }else if(flag == "0"){
                if(callback0 && typeof callback0 == 'function'){
                    params ? callback0(params):callback0();
                }
            }
        });
        $('#myModal').modal({backdrop: "static",keyboard:false,show:true});//点击背景空白处不会关闭；按下键盘esc不会被关闭
    };
    event.getIds = function(arrObj){
        var arr =[];
        for(var i = 0;i<arrObj.length;i++){
            arr.push(arrObj[i].id);
        }
        return arr;
    };
    event.delId = function(ids,id){
        var index = ids.indexOf(id);
        if (index >= 0) {
            if($("#"+id).parent().attr("isEnding") == 'end'){
                ids.splice(index, 1);
            }
        }
        return ids;
    };
    return event;
});